package org.fao.pims.persistence;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.sql.*;
import java.util.*;
import org.apache.commons.logging.*;
import org.fao.pims.model.*;

public class AgentDaoImpl extends BaseDao implements AgentDao {

	private static Log log = LogFactory.getLog(PollinationNeedDaoImpl.class);

	public List getDocAgents(Document doc) {
		
		PreparedStatement pstmt = null;
        ResultSet rset = null;
        Connection conn = null;
        List result = new ArrayList();
      
        try {
        	conn = this.getDatasource().getConnection();         

        	String query = 
        		"SELECT agn.*" +
        		"  FROM bib_document_agent dxa," +
        		"       bib_agent agn" +
        		" WHERE agn.id = dxa.agent_id" +
        		"   AND dxa.document_id = " + doc.getId();   
        	
        	System.out.println(query);
        	
        	pstmt = conn.prepareStatement(query);
            rset = pstmt.executeQuery();    
            result = makeBeanList(resultsetToList(rset));
        } 
        catch(SQLException e) {
            e.printStackTrace();
        }
        finally {
            try 
            { 
                if( ! conn.isClosed() )
                    conn.close(); 
                System.out.println("Connection closed");
            }
            catch(Exception e) {
                e.printStackTrace();
            }
        }
		
		return result;
	}

	@Override
	protected List makeBeanList(List rows) {
		List beanList = new ArrayList();
        
		System.out.println("rows size: "+ rows.size());
        ListIterator rowIterator = rows.listIterator();
        int rowcounter = 0;
        while(rowIterator.hasNext())
        {
            rowcounter++;
            List fieldlist = (List)rowIterator.next();
            ListIterator fieldsIterator = fieldlist.listIterator();
            Object obj = null;
            String type = "";
            String columnName = "";
            Agent bean = new Agent();
            
            while(fieldsIterator.hasNext())
            {
                TableFieldHandler tfhandler = (TableFieldHandler)fieldsIterator.next();
                obj = tfhandler.getObject();
                type = tfhandler.getType();
                columnName = tfhandler.getColumnName().trim();
                // System.out.println(columnName);
                if( obj != null ) {
	                if( "ID".equalsIgnoreCase(columnName) )
	                {
	                    bean.setId( ((Integer)obj).intValue() );                
	                }                	                
	                if( "NAME".equalsIgnoreCase(columnName) )
	                {
	                    bean.setName( (String)obj );                    
	                }
	            }
            }
            beanList.add(bean);
         }
        return beanList;
	}
}
